package com.xiaoxu.privatechat.controller.common;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;


/**
 * @author xiaoxu
 * @description 下载控制器统一管理类
 * @date 2023/2/13
 */
@RequestMapping("/download")
@Controller
public class DownloadController {

    /**
     * 文件保存位置
     */
    @Value("${ylrc.upload.file.path}")
    private String uploadFilePath;

    /**
     * @description 统一文件下载方法
     * @param filename 文件名称
     * @param downloadname 下载名称
     * @param response Http响应
     */
    @RequestMapping(value = "/download_file")
    public void downloadFile(@RequestParam(name = "filename") String filename,
                             @RequestParam(name = "downloadname", defaultValue = "") String downloadname,
                             HttpServletResponse response) {
        if (StringUtils.isEmpty(downloadname)) {
            downloadname = filename;
        }
        try {
            File file = new File(uploadFilePath + filename);
            response.setContentLength(Integer.parseInt(file.length() + ""));
            response.setContentType(Files.probeContentType(Paths.get(uploadFilePath + filename)));
            String suffix = filename.substring(filename.lastIndexOf("."));
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(downloadname.getBytes(StandardCharsets.UTF_8), "ISO8859-1") + suffix);
            writefile(response, file);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }


    /**
     * @description 写文件 方法
     * @param response 响应
     * @param file 文件
     */
    public void writefile(HttpServletResponse response, java.io.File file) {
        byte[] buff = new byte[1024];
        FileInputStream fis;
        BufferedInputStream bis;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            ServletOutputStream outputStream = response.getOutputStream();
            int i = bis.read(buff);
            while (i != -1) {
                outputStream.write(buff, 0, i);
                i = bis.read(buff);
            }
            bis.close();
            fis.close();
        } catch (Exception e) {
            //e.printStackTrace();
        }

    }

}
